package com.eeepay.eeepay_v2.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.eeepay.v2_library.bitmap.Bimp;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABFileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public abstract class ABPhotoActivity extends ABBaseActivity {

    private final int PHOTO_PZ = 10;// 拍照
    private final int PHOTO_XC = 20;// 从相册中选择
    private final int PHOTO_CJ = 30;// 结果

    File fileCamera;// 拍照或裁减文件的跟目录
    File file;// 拍照时，拍照图片临时保存文件
    String nowPath = "";
    // String tempPath = "";
//	int picSize = 240;

    public int width = 0;
    public int height = 0;
    private final int CODE_FOR_WRITE_PERMISSION=0;
    /**
     * @return 拍照文件保存路径（目录）
     */
    protected abstract String getPhotoPath();


    /**
     * @param imgFile
     * @param bitmap
     */
    protected abstract void selectPhotoPathResult(File imgFile, Bitmap bitmap);


    protected void setNowPath(String nowPath) {
        this.nowPath = nowPath;
    }

    @Override
    protected void onStart() {
        super.onStart();
        fileCamera = new File(ABFileUtil.SD_CARD_PATH, getPhotoPath());
        if (!fileCamera.exists()) {
            fileCamera.mkdirs();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_PZ:
                    if (file != null) {
                        try {
                            int degree = Bimp.readPictureDegree(file.getAbsolutePath());
                            Bitmap bitmap = Bimp.compressBitmap(file.getAbsolutePath(), width == 0 ? 100 : width, height == 0 ? 100 : height);
                            File imageFile = null;
                            if (TextUtils.isEmpty(nowPath)) {
                                imageFile = new File(fileCamera, new Date().getTime() + ".jpg");
                            } else {
                                imageFile = new File(fileCamera, nowPath + ".jpg");
                            }
                            Bitmap newbitmap = Bimp.rotaingImageView(degree, bitmap);
                            FileOutputStream fos = new FileOutputStream(imageFile);
                            newbitmap.compress(CompressFormat.JPEG, 100, fos);
                            selectPhotoPathResult(imageFile, newbitmap);
                            fos.flush();
                            fos.close();
                            bitmap.recycle();
                            newbitmap.recycle();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                    break;

                case PHOTO_XC:
                    if (data != null) {
//						startPhotoZoom(data.getData(), width == 0 ? 100 : width, height == 0 ? 100 : height);
                        Uri uri = data.getData();
                        File imgFile ;
                        Bitmap bitmap = null;
                        if (TextUtils.isEmpty(nowPath)) {
                            imgFile = new File(fileCamera, new Date().getTime() + ".jpg");
                        } else {
                            imgFile = new File(fileCamera, nowPath + ".jpg");
                            bitmap=Bimp.createBitmap(this, uri, imgFile);
                        }
                        selectPhotoPathResult(imgFile, bitmap);
                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

//

    /**
     * 照相机选择图片
     */
    protected void selectCamera() {
        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            Activity activty=this;
            ActivityCompat.requestPermissions(activty,new String[] {Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},
                    CODE_FOR_WRITE_PERMISSION);
            return;
        }
        file = new File(fileCamera, new Date().getTime() + ".jpg");
        Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent1, PHOTO_PZ);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CODE_FOR_WRITE_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    file = new File(fileCamera, new Date().getTime() + ".jpg");
                    Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    startActivityForResult(intent1, PHOTO_PZ);
                } else {
                    // Permission Denied
                    Toast.makeText(ABPhotoActivity.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 相册选择图片
     */
    protected void selectAlbum() {
        Intent intent2 = new Intent(Intent.ACTION_PICK, null);
        intent2.setType("image/*");
//		intent2.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent2, PHOTO_XC);
    }

//    case PHOTO_CJ:
//                    if (data != null) {
//                        File imageFile = null;
//                        Bundle bundle = data.getExtras();
//                        Bitmap bitmap = null;
//                        try {
//                            if (bundle != null) {
//                                bitmap = bundle.getParcelable("data");
//                                if (TextUtils.isEmpty(nowPath)) {
//                                    imageFile = new File(fileCamera, new Date().getTime() + ".jpg");
//                                } else {
//                                    imageFile = new File(fileCamera, nowPath + ".jpg");
//                                }
//
//                                if (!imageFile.exists()) {
//                                    imageFile.createNewFile();
//                                }
//                                FileOutputStream fos = new FileOutputStream(imageFile);
//                                bitmap.compress(CompressFormat.JPEG, 100, fos);
//                                fos.flush();
//                                fos.close();
//
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        selectPhotoPathResult(bitmap, imageFile.getPath());
//                    }
//                    break;

//    private void startPhotoZoom(Uri uri, int width, int height) {
//        try {
//            Intent intent = new Intent("com.android.camera.action.CROP");
//            intent.setDataAndType(uri, "image/*");
//            // crop为true是设置在开启的intent中设置显示的view可以剪裁
//            intent.putExtra("crop", "true");
//            // aspectX aspectY 是宽高的比例
//            intent.putExtra("aspectX", width);
//            intent.putExtra("aspectY", height);
//            // outputX,outputY 是剪裁图片的宽高
//            intent.putExtra("outputX", width);
//            intent.putExtra("outputY", height);
//            intent.putExtra("return-data", true);
//            intent.putExtra("scale", true);
//            intent.putExtra("outputFormat", CompressFormat.JPEG.toString());
//            intent.putExtra("noFaceDetection", true); // no face detection
//            startActivityForResult(intent, PHOTO_CJ);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
}
